//
//  XMIntroduceViewController.m
//  XunMi
//
//  Created by MacBook on 2024/2/27.
//  Copyright © 2024 TieZhu. All rights reserved.
//

#import "XMIntroduceViewController.h"

static NSInteger kMaxNumber = 200;

@interface XMIntroduceViewController () <UITextViewDelegate>
@property (weak, nonatomic) IBOutlet UITextView *textView;
@property (weak, nonatomic) IBOutlet UILabel *countLa;
@property (weak, nonatomic) IBOutlet UIView *bgV;
@end

@implementation XMIntroduceViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navLeft2Btn setTitle:@"自我介绍" forState:UIControlStateNormal];
    [self.navRightBtn setTitle:@"保存" forState:UIControlStateNormal];
    [self.navRightBtn mas_updateConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(66, 32));
    }];
    [self.navRightBtn setBackgroundColor:kAppMainColor];
    [self.navRightBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    [self.navRightBtn addTarget:self action:@selector(save) forControlEvents:UIControlEventTouchUpInside];
    
    kCornerRadius(self.navRightBtn, 16, 0, UIColor.clearColor);
    kCornerRadius(self.bgV, 10, 0, UIColor.clearColor);
    
    self.textView.placeholder = @"请填写自我介绍...";
    self.textView.placeholderColor = kHEX(@"9A9A9A");
    self.textView.delegate = self;
    self.textView.text = self.introduce;
    self.countLa.text = kStringFormat(@"%ld/%ld", self.introduce.length, kMaxNumber);

}

#pragma mark - Actions
- (void)save {
    if (self.textView.text.length == 0) {
        [MBProgressHUD showHUDMsg:@"请填写自我介绍哦" toView:nil];
        return;
    }
    [self.textView resignFirstResponder];
    [MBProgressHUD showHUDActivityMsg:nil toView:kWindow];
    NSMutableDictionary *dic = @{
        @"introduce":self.textView.text
    }.mutableCopy;
    [YHNetworkManager.sharedInstance postWithUrl:@"api/user/update" parameters:dic completeBlock:^(XMResponseTip * _Nonnull tip, id  _Nullable result) {
        if (tip.success) {
            [MBProgressHUD hideHUD];
            if (self.saveBlock) {
                self.saveBlock(self.textView.text);
            }
            [self backAction];
        }
    }];
}

- (void)textViewDidChange:(UITextView *)textView {
    // 处理字符变化的逻辑
    NSLog(@"Text changed: %@", textView.text);
    if (textView.text.length > kMaxNumber) {
        textView.text = [textView.text substringWithRange:NSMakeRange(0, kMaxNumber)];
    }
    self.countLa.text = kStringFormat(@"%ld/%ld", textView.text.length, kMaxNumber);
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }
    return YES;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

@end
